#include "zlist.h"
#include <stdio.h>
#include <stdlib.h>
#include "zmath.h"

pzlist zlist_create()
{
	pzlist pobj = (pzlist)calloc(1, sizeof(zlist));
	return pobj;
}

int zlist_add(pzlist pobj, void * item)
{
	int ret = -1;
	int lennew = 0;
	int lennewpow = 0;
	void ** reallocr = NULL;
	if (NULL == pobj)
	{
		ret = -1;
		return ret;
	}

	//(void **)calloc(pobj->m_len + 1, sizeof(void *))
	lennew = pobj->m_len + 1;
	if (pobj->m_capacity < lennew)
	{
		lennewpow = zmath_getnextpowof2(lennew);
		reallocr = (void **)realloc(pobj->m_data, lennewpow * sizeof(void *));
		if (NULL == reallocr)
		{
			ret = -1;
			return ret;
		}

		// realloc suc
		pobj->m_data = reallocr;
		pobj->m_capacity = lennewpow;
	}
	
	(pobj->m_data)[pobj->m_len] = item;
	pobj->m_len++;
	return 0;
}

int zlist_clear(pzlist pobj, void(*cb)(void * item))
{
	int ret = -1;
	int i = 0;

	if (cb == NULL || pobj == NULL)
	{
		return ret;
	}
	
	// del the member m_data
	if (pobj != NULL)
	{
		if (pobj->m_data != NULL)
		{
			// only free every mem of items point to
			for (i = 0; i < pobj -> m_len; i++)
			{
				if (cb != NULL)
				{
					cb((pobj->m_data)[i]);
					(pobj->m_data)[i] = NULL;
				}
			}		
		}
	}
	return 0;
}

void zlist_delete(pzlist * ppobj)
{
	if (NULL == ppobj)
	{	
		return;	
	}

	// del the member m_data
	if ((*ppobj) != NULL)
	{
		if ((*ppobj)->m_data != NULL)
		{
			free((*ppobj)->m_data);
			(*ppobj)->m_data = NULL;
		}
	}
}
